import Vue from 'vue'
import Vuex from 'vuex'
import axios from '../utils/axios'

// import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: []
  },
  mutations: {
    setList(state, payload) {
      let localData = localStorage.getItem('vuex')
      state.list =localData?JSON.parse(localData).list : payload
    },
    delete(state, payload) {
     
      let index = state.list.findIndex(item => item.id === payload)
      if (index !== -1) {
        state.list.splice(index, 1)
      }
    },
    addItem(state,payload){
      console.log(payload);
      state.list.push(payload)
    },
    editItem(state, payload) {
      state.list.forEach((item) => {
        if (item.id === payload.id) {
          item = payload;
        }
      });
    },
  },
  actions: {
    async getList({
      commit
    }) {
      let res = await axios.get('/api/list')
      commit('setList', res.data.list)
    }
  },
  modules: {},
  plugins: [createPersistedState()],
})